package com.bcx.wind.workflow.imp.cmd.repositorycmd.processconfigcmd;

import com.bcx.wind.workflow.entity.WindProcessConfig;
import com.bcx.wind.workflow.errorcontext.WindError;
import com.bcx.wind.workflow.interceptor.Command;
import com.bcx.wind.workflow.interceptor.CommandContext;

import static com.bcx.wind.workflow.message.ErrorCode.*;

/**
 * 删除流程定义配置命令  可以通过主键和流程定义ID删除
 *
 * @author zhanglei
 */
public class RemoveProcessConfigByIdCommand implements Command<Integer> {

    /**
     * 配置ID
     */
    private String configId;

    /**
     * 执行数据
     */
    private CommandContext commandContext;

    /**
     * 需要删除的流程配置数据
     */
    private WindProcessConfig windProcessConfig;

    public RemoveProcessConfigByIdCommand(String configId){
        this.configId = configId;
    }


    @Override
    public Integer executor(CommandContext context) {
        try{
            this.commandContext = context;
            return execute();
        }catch (Exception e){
            commandContext.log(e);
            return null;
        }
    }

    private Integer execute(){
        //校验参数
        checkArgs();
        //执行删除
        int ret = remove();
        //删除缓存
        this.commandContext.getConfiguration().removeProcessConfigCache(this.windProcessConfig.getProcessId(),this.configId);
        return ret;
    }

    private int remove(){
        int ret = this.commandContext.access().removeProcessConfigById(configId);
        if(ret != 1){
            WindError.error(DATABASE_OPERATE_ERROR,null);
        }
        return ret;
    }


    /**
     * 校验参数
     */
    private void checkArgs(){
        if(this.configId == null){
            WindError.error(OPERATE_FAIL,null,"processConfig","remove","configId");
        }
        this.windProcessConfig = this.commandContext.access().getProcessConfigById(configId);
        if(this.windProcessConfig == null){
            WindError.error(QUERY_EMPTY,null,"processConfig",configId);
        }
    }
}
